//
//  HomeViewController.m
//  pz_live
//
//  Created by caiyc on 2018/9/17.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "HomeViewController.h"
#import "Live_Cell.h"
#import "AreaViewController.h"
#import "RegistFViewController.h"
#import "LoginViewController.h"
#import "UserinfoViewController.h"
#import "LiveViewController.h"
#import "PlayViewController.h"
#import "Regist2ViewController.h"
#import "NotiViewController.h"
#import "LiveCatogryViewController.h"
#import "Index_LiveViewController.h"
#import "Index_StaicViewController.h"
#import "UserionfsViewController.h"
#import "ShortVideoViewController.h"
#import "SPRollView.h"
@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSMutableArray *dataSouce;
@property(assign)NSInteger cutdown_time;
@property (nonatomic ,strong)dispatch_source_t timer;
@property(assign)CGFloat nomalHeight;

@end

@implementation HomeViewController
//
-(NSString *)getMMSSFromSS:(NSInteger )totalTime{
    
    NSInteger seconds = totalTime;
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%ld",(seconds/60)];
    if(str_minute.length>1){
        self.time_1.text = [str_minute substringWithRange:NSMakeRange(0, 1)];
        self.time_2.text =  [str_minute substringWithRange:NSMakeRange(1, 1)];
    }else{
        self.time_2.text = str_minute;
    }
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%ld",(seconds%60)];
    if(str_second.length>1){
        self.time_3.text = [str_second substringWithRange:NSMakeRange(0, 1)];
        self.time_4.text =  [str_second substringWithRange:NSMakeRange(1, 1)];
    }else{
        self.time_3.text = @"0";
        self.time_4.text = str_second;
    }
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@分钟%@秒",str_minute,str_second];
    
  //  NSLog(@"format_time : %@",format_time);
    
    return format_time;
}
//切换地区
- (IBAction)changeArea:(UIButton *)sender {
    AreaViewController *vc = [[AreaViewController alloc]init];
    vc.city=^(NSDictionary *dic){
        [self.city_Btn setTitle:dic[@"name"] forState:UIControlStateNormal];
        //后续根据区域选择直播
    };
    [self pushSecondVC:vc];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(![XTool GetDefaultInfo:USER_INFO]){
        [WToast showWithText:@"请先登录"];
        LoginViewController *vc = [[LoginViewController alloc]init];
        [self pushSecondVC:vc];
    }else{
        NSInteger index = self.botom_ScroView.contentOffset.x/screen_width;
        if(index==0){
        self.botom_ScroView.frame = CGRectMake(0, 0, screen_width, self.view.frame.size.height);
        }else{
            self.botom_ScroView.frame = CGRectMake(0, 0, screen_width, self.view.frame.size.height-63);
        }
       // self.botom_ScroView.backgroundColor = [UIColor clearColor];
       // self.botom_ScroView.backgroundColor = [UIColor redColor];
    }
    [[SPRollView shareInstance] startAnimation];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[SPRollView shareInstance] stopAnimation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadLiveLis) name:@"enterforhead" object:nil];;
    
    if (@available(iOS 11.0, *)) {
        self.botom_ScroView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self setViews];
    // Do any additional setup after loading the view from its nib.
}
-(void)setViews{
    self.botom_ScroView.contentSize = CGSizeMake(screen_width*3, self.botom_ScroView.frame.size.height);
   self.botom_ScroView.scrollEnabled = 0;
//    self.botom_ScroView.pagingEnabled = 1;
    self.nomalHeight =  self.botom_ScroView.frame.size.height-63;
    ShortVideoViewController *vc1 = [[ShortVideoViewController alloc]init];
    vc1.view.frame =  CGRectMake(screen_width*2, 0,  self.botom_ScroView.frame.size.width, self.botom_ScroView.frame.size.height);
    [self.botom_ScroView addSubview:vc1.view];
    [self addChildViewController:vc1];
    
    Index_LiveViewController *vc = [[Index_LiveViewController alloc]init];
    vc.view.frame = CGRectMake(screen_width*1, 0,  self.botom_ScroView.frame.size.width, self.botom_ScroView.frame.size.height);
    [self.botom_ScroView addSubview:vc.view];
    [self addChildViewController:vc];
    
    Index_StaicViewController *vc0 = [[Index_StaicViewController alloc]init];
    vc0.view.frame = CGRectMake(0, 0, self.botom_ScroView.frame.size.width, self.botom_ScroView.frame.size.height);
    [self.botom_ScroView addSubview:vc0.view];
    [self addChildViewController:vc0];
    
    self.botom_ScroView.contentOffset = CGPointMake(screen_width, 0);//进入首页默认中间选项
    self.search_View.layer.cornerRadius = 19;
    self.search_View.layer.masksToBounds = 1;
    //NSLog(@"判断设备型号：%d",KISIphoneX);
    self.view.backgroundColor = viewcontrollerColor;
//    self.tableView.backgroundColor = viewcontrollerColor;
//    self.tableView.delegate = self;
//    self.tableView.dataSource = self;
   // self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadLiveLis)];
    //  [self.tableView.mj_header beginRefreshing];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.icon_Img.userInteractionEnabled = 1;
    self.icon_Img.layer.cornerRadius = 15;
    self.icon_Img.layer.masksToBounds = 1;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapimage)];
    [self.icon_Img addGestureRecognizer:tap];
    self.dataSouce = [NSMutableArray array];
    self.segementView.layer.cornerRadius = 20;
    self.segementView.backgroundColor = viewcontrollerColor;
    self.segementView.layer.masksToBounds = 1;
    [self.live_V_Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //RGB(254, 220, 68);
    [self.live_V_Btn setBackgroundColor:RGB(254, 220, 68)];
    self.live_V_Btn.layer.cornerRadius = 20;
    [self.live_V_Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.live_V_Btn setTitle:@"◀直播" forState:UIControlStateNormal];
    [self.index_Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.index_Btn.layer.cornerRadius = 20;
    [self.short_V_Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.short_V_Btn.layer.cornerRadius = 20;
}
-(void)setBtnStyle:(UIButton *)btn andStyle:(NSInteger)type{
    
}
//抢购倒计时
-(void)cutdown{
    __block  NSInteger start = 0;
    start = self.cutdown_time;
    //0.创建队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    
    //3.要调用的任务
    dispatch_source_set_event_handler(timer, ^{
        if(start<0){
            //到下一时段，自动刷新页面数据
            //  [self loadLiveLis];
            }else{
            [self getMMSSFromSS:start];
            start--;
            }
    });
    
    //4.开始执行
    dispatch_resume(timer);
    
    //
    self.timer = timer;
    
}
//获取直播列表
-(void)loadLiveLis{
    [self.dataSouce removeAllObjects];
    NSDictionary *param = @{@"ac":@"store",@"op":@"activity",@"ctrl":@"live"};
    [self weqPostHandle:param success:^(id response) {
        [self.tableView.mj_header endRefreshing];
        
        if(response){
            NSArray *acti_Arr = response[@"data"][@"activity_list"];
            if(acti_Arr.count==0){
                [WToast showWithText:@"此时段暂无直播"];
                self.count_lab.text =@"本时段暂无直播";
                //  [self.dataSouce addObjectsFromArray:response[@"data"][@"activity_list"]];
            }else{
                self.count_lab.text = [NSString stringWithFormat:@"本场直播 %lu",(unsigned long)acti_Arr.count];
                [self.dataSouce addObjectsFromArray:response[@"data"][@"activity_list"]];
            }
            self.cutdown_time= [response[@"data"][@"end_time_field"]integerValue]-[response[@"data"][@"service_time"]integerValue];
            [self cutdown];
            [self.tableView reloadData];
            }else{
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
        
    }];
}
-(void)tapimage{

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"sells";
    Live_Cell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell){
        cell = [[[NSBundle mainBundle]loadNibNamed:@"Live_Cell" owner:self options:nil]lastObject];
    }
    [cell bindData:self.dataSouce[indexPath.row]];
    return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSouce.count+10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 267;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = [self.dataSouce objectAtIndex:indexPath.row];
    PlayViewController *vc = [[PlayViewController alloc]init];
    vc.live_id = [NSString stringWithFormat:@"%@",dic[@"id"]];
    [self pushSecondVC:vc];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)checkNoti:(id)sender {
    NotiViewController *vc = [[NotiViewController alloc]init];
    [self pushSecondVC:vc];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"stopshort" object:nil];
}
//点击分类
- (IBAction)clickCatogy:(UIButton *)sender {
    LiveCatogryViewController *vc = [[LiveCatogryViewController alloc]init];
    [self pushSecondVC:vc];
}

- (IBAction)chekUserinfo:(id)sender {
    if(![XTool GetDefaultInfo:USER_INFO]){
        LoginViewController *vc = [[LoginViewController alloc]init];
        [self pushSecondVC:vc];
    }else{
        UserionfsViewController *vc = [[UserionfsViewController alloc]init];
        [self pushSecondVC:vc];

    }
      [[NSNotificationCenter defaultCenter]postNotificationName:@"stopshort" object:nil];
}
- (IBAction)seges:(UIButton *)sender {
    [self.left_Btn setImage:[UIImage imageNamed:@"notivces"] forState:UIControlStateNormal];//person12
    [self.right_Btn setImage:[UIImage imageNamed:@"person12"] forState:UIControlStateNormal];
    if(sender.tag==0){
    //  self.botom_ScroView.frame = CGRectMake(0, 0, screen_width, self.nomalHeight);
        self.botom_ScroView.frame = CGRectMake(0, 0, screen_width, self.view.frame.size.height-63);
        self.botomView.backgroundColor = [UIColor whiteColor];
        self.segementView.backgroundColor = viewcontrollerColor;
        [[NSNotificationCenter defaultCenter]postNotificationName:@"changtoShort" object:nil];
      //  [WToast showWithText:@"暂无短视频数据"];
        [self.botom_ScroView setContentOffset:CGPointMake(screen_width*2, 0) animated:YES];
        //RGB(254, 220, 68);
        [self.short_V_Btn setBackgroundColor:RGB(254, 220, 68)];
        [self.short_V_Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        // self.live_V_Btn.layer.cornerRadius = 24;
        [self.short_V_Btn setTitle:@"◀短视频" forState:UIControlStateNormal];
        self.live_V_Btn.backgroundColor = viewcontrollerColor;
        [self.live_V_Btn setTitle:@"直播" forState:UIControlStateNormal];
         [self.live_V_Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        self.index_Btn.backgroundColor = viewcontrollerColor;
        [self.index_Btn setTitle:@"首页" forState:UIControlStateNormal];
         [self.index_Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
    }else if(sender.tag==1){
        self.botom_ScroView.frame = CGRectMake(0, 0, screen_width, self.view.frame.size.height-63);
        self.botomView.backgroundColor = [UIColor whiteColor];
        self.segementView.backgroundColor =viewcontrollerColor;
         [[NSNotificationCenter defaultCenter]postNotificationName:@"stopshort" object:nil];
        [self.botom_ScroView setContentOffset:CGPointMake(screen_width, 0) animated:YES];
        [self.live_V_Btn setBackgroundColor:RGB(254, 220, 68)];
        [self.live_V_Btn setTitle:@"◀直播" forState:UIControlStateNormal];
        [self.live_V_Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.short_V_Btn.backgroundColor = viewcontrollerColor;
        [self.short_V_Btn setTitle:@"短视频" forState:UIControlStateNormal];
         [self.short_V_Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        self.index_Btn.backgroundColor = viewcontrollerColor;
        [self.index_Btn setTitle:@"首页" forState:UIControlStateNormal];
         [self.index_Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }else{
      
      self.botomView.backgroundColor = RGBA(255, 255, 255, 0);
         self.segementView.backgroundColor = RGB(70, 77, 140);
        [self.view bringSubviewToFront:self.botomView];
       // self.botomView.backgroundColor = [UIColor clearColor];
        self.botom_ScroView.frame = CGRectMake(0, 0, screen_width, self.view.frame.size.height);
        [[NSNotificationCenter defaultCenter]postNotificationName:@"stopshort" object:nil];
        [self.botom_ScroView setContentOffset:CGPointMake(0, 0) animated:YES];
        //[self.live_V_Btn setBackgroundColor:RGB(254, 220, 68)];
        self.live_V_Btn.backgroundColor = [UIColor clearColor];
        [self.live_V_Btn setTitle:@"直播" forState:UIControlStateNormal];
        [self.live_V_Btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.short_V_Btn.backgroundColor = [UIColor clearColor];
        [self.short_V_Btn setTitle:@"短视频" forState:UIControlStateNormal];
        [self.short_V_Btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.index_Btn.backgroundColor = RGB(82, 74, 255);
        [self.index_Btn setTitle:@"首页▶" forState:UIControlStateNormal];
        [self.index_Btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        self.leftImg.image = [UIImage imageNamed:@"persons"];
//        self.rightImg.image = [UIImage imageNamed:@"person1"];
        [self.left_Btn setImage:[UIImage imageNamed:@"ppp"] forState:UIControlStateNormal];
        [self.right_Btn setImage:[UIImage imageNamed:@"person11"] forState:UIControlStateNormal];
        
    }
}
@end
